/**
 * Created by Administrator on 2017/7/26.
 */


$(document).ready(function () {

	//广告
	var protpl = $("#swiper-pro").html();
	var proTemplate = Handlebars.compile(protpl);
	
    //商品信息
    var shoptpl=$('#discount-list-template').html();
    var shopTemplate=Handlebars.compile(shoptpl);

    //京东广告
    var jdfltpl = $("#swiper-jdfl").html();
    var jdflTemplat = Handlebars.compile(jdfltpl);
    
    //今日爆款
    var nowexpension = $("#swiper-explosion").html();
    var nowexpensionTemplat =  Handlebars.compile(nowexpension);
    //ajax加载商品列表
    var range = 200, //距下边界长度/单位px
        maxnum = 0, //设置课程总数
        num = 0, //当前数量
        totalheight = 0,
        flag=0,
        start=0,
        pageLength=20,
        keyword='',
        ids,
        orderType,
        minMaxPrice;
    	
    ajaxGetShopData();

    //监听滚动高度，加载数据
    $(window).on('scroll',function () {
        var srollPos = $(window).scrollTop(); //滚动条距顶部距离(页面超出窗口的高度)
        //console.log("滚动条到顶部的垂直高度: " + $(document).scrollTop());
        //console.log("页面的文档高度 ："+$(document).height());
        //console.log('浏览器的高度：'+$(window).height());
        totalheight = parseFloat($(window).height()) + parseFloat(srollPos);

        /*if (num>=maxnum){
            return;
        }*/
        if (($(document).height()-range)<=totalheight){
                                                    /*&&num<maxnum*/
            //这里不能使用模板填充，应该是append()....
            ajaxGetShopData();
        }
    });

    function ajaxGetShopData() {
        if (flag){
            return;
        }
        $('.loading').show();
        flag=1;
        $.ajax({
            url:C.interface.jdShop,
            type:'get',
            dataType:'json',
            data:{
                token:C.token,
                start:start,
                length:pageLength,
                keyword:keyword,
                categoryId:ids,
                orderType:orderType,
                minMaxPrice:minMaxPrice
            },
            success:function (response) {
            	console.log(response);
                if (response.result=='success'){

                    $('.loading').hide();
                    num++;
                    var data=response.data;
                    maxnum=data.list.length;
                    start=num*pageLength;
                    if(maxnum == 0){
                        $(".no-info").show();
                    }
                    
                    $(".todaygood-ul").html(nowexpensionTemplat(data));
                    var len = data.baokuans.length;
                   
                    if(len == 0){
                    	$(".todaygood").hide();
                    }else{
                    	 var seckhigh = 300.17*len;
                         $("#seckill").css("width",seckhigh);
                         
                         
                    }
                    $('#aui-slide3').html(proTemplate(data));
                    //轮播图
                    var slide3 = new auiSlide({
                        container:document.getElementById("aui-slide3"),
                        // "width":300,
                        //"height":213,
                        "speed":500,
                        "autoPlay": 3000, //自动播放
                        "loop":true,
                        "pageShow":true,
                        "pageStyle":'dot',
                        'dotPosition':'center'
                    });
                   

                    
                    //console.log(data.list.length);
                    if (data.list.length>0){
                        $('#dis-list-vessel').append(shopTemplate(data));
                        //$(".display-box").bind("click",jdDetail)
                        new auiLazyload({
                            errorImage:'../image/errorimg.png'
                        });


                    }else {
                        $(".no-info").show();
                        num=maxnum+1;
                    }
                    $('.dis-list-box').bind('click',getJumpPage);
                    flag=0;
                }else if (response.result === 'login'){
                    dialog.tusiError('登录过期请重新登录');
                    againLogin();

                }else {
                    dialog.tusiError(response.errorMsg);
                }
            },
            error:function () {
                //dialog.tusiError('服务器异常');
            }
        });
    }
//京东点击详情页
   function jdDetail(){
	   var data = {
			 postType: 'jdDetail'  
	   }
	   var ua = navigator.userAgent.toLowerCase();
       if (/iphone|ipad|ipod/.test(ua)) {

           jdretbut(data);
           event.stopPropagation();
       }
   }
 function jdretbut(parm){
	 window.webkit.messageHandlers.jdreturnbut.postMessage(param);
 }
    //京东分类
    $.ajax({
        url:C.interface.jdfl,
        type:'get',
        dataType:'json',
        success:function (data) {
         // console.log(response)
          var len = data.data.length;
          var allwidth = 91*len;
      		$(".classify-ul").css('width',allwidth);
      		$('.classify-ul').append(jdflTemplat(data));
      		newjdevent();
        }
    });
    
    /************/
    $(".dis-screen-btn").click(function(){
    	$(".dis-screen").show();
    	$(".rDialog-mask").show();
    })
    $(".cancel").click(function(){
    	$(".dis-screen").hide();
    })
     $(document).on('change','.dis-shop-sort',function () {
                    $('#dis-list-vessel').empty();
                    orderType=$(this).val();
                    console.log(orderType);
                    num=0;
                    start = num;
                    ajaxGetShopData();
                    // $('.dis-screen').hidden();
                });
   $("#nmbConfirm").click(function(){
	   var lowPrice=$('.dis-low-price').val();
       //          最高价
       var highPrice=$('.dis-high-price').val();
       console.log(lowPrice,highPrice);
       if(parseInt(lowPrice)>parseInt(highPrice)){
    	  
    	   dialog.tusiError('最低价不能大于最高价');
       }
       minMaxPrice = lowPrice+'-'+highPrice;
       $('.dis-screen').toggle();
       $('#dis-list-vessel').empty();
     //清空搜索数据
       $('.dis-low-price').val('');
       $('.dis-high-price').val('');
       $('.dis-low-sales').val('');
       $('.dis-high-sales').val('');
       num =start = 0;
       ajaxGetShopData();
   })
    
    function getJumpPage() {
	   
	   //dialog.tusiSuccess('即将进入京东页面');
	   $(".maskcon").show();
	   event.preventDefault();
	   var that = $(this);
       var id = that.data('id');
      // var loading = dialog.loading();
	   setTimeout(function(){
	       
		   $(".maskcon").hide();
	        $.ajax({
	            url:C.interface.erHeYi,
	            type:'get',
	            dataType:'json',
	            data:{
	                token:C.token,
	                id:id
	            },
	           
	            success:function (response) {
	                if (response.result === 'success'){
	                    var data = response.data;
	                    location.href = data;
	                }else if (response.result === 'login'){
	                    dialog.tusiError('请重新登录');
	                    againLogin();
	                }else {
	                    dialog.tusiError(response.errorMsg);
	                }
	            }
	        });
	   },1000)
    }


    // $(document).on('click','#nmbConfirm',getScreen);
    $('.all-mask').bind('click',function () {
        $('.dis-screen-price').hide();
    });


    //搜索数据
    $('.aui-searchbar-btn').bind('click',jdSearch);
    //取消搜索
    $('#clean-search').bind('click',cancelSearch);

    function jdSearch() {

        keyword = $('#search-input').val();
        if (keyword == '' ){
            return false;
        }else {
            $('#dis-select-box').hide();
            $('#dis-list-vessel').empty();
            $(".todaygood-ul").empty();
            num = start = 0;
            ajaxGetShopData();
        }

    }
    //京东分类点击事件
    function newjdevent(){
    	$(".classify-ul li").eq(0).addClass('addsty');
    	$(".classify-ul li").click(function(){
    	var index = $(this).index();
    	$(".classify-ul li").removeClass('addsty');
    	$(".classify-ul li").eq(index).addClass('addsty');
    	
       	 event.preventDefault();
       	 ids = $(this).attr('data_id');
       	 $('#dis-select-box').hide();
            $('#dis-list-vessel').empty();
            
            num = start = 0;
            ajaxGetShopData();
       	 
       })
    }
    
    function cancelSearch() {
        $('.no-info').hide();
        $('#dis-select-box').show();
        $('#dis-list-vessel').empty();
        $(".todaygood-ul").empty();
        keyword = '';
        num = start = 0;
        ajaxGetShopData();
    }






    //
    Handlebars.registerHelper('hongbao',function (sales) {
        if (sales==null){
            return null;
        }else {
            return sales;
        }
    });
    //包邮不包邮
    Handlebars.registerHelper('exemption',function (value) {
        if (value=='001'){
            return '退货免邮费';
        }else if (value=='002'){
            return '退货不包邮';
        }
    });

});


$(document).ready(function () {
    new auiLazyload({
        errorImage:'../image/errorimg.png'
    });
});

$(function(){
	$(".menusea").click(function(){
		//alert('11');
		if($("#dis-select-box").height() == 0){
			$("#dis-select-box").animate({height:"2rem"});
			$("#dis-select-box").show();
		}else{
			$("#dis-select-box").animate({height:"0rem"});
			$("#dis-select-box").hide();
		}
	})
	
})
